import { defineStore } from 'pinia'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter()
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)

  const login = async (credentials) => {
    console.log('Login function triggered')  // 新增测试日志
    try {
      const response = await axios.post('http://117.72.45.141:8091/api/user/login', credentials)
      token.value = response.data.data.token
      console.log('Token value after login:', token.value)  // 新增调试日志
      localStorage.setItem('token', token.value)
      user.value = response.data.user
      console.log('User value after login:', user.value)  // 新增调试日志
    } catch (error) {
      throw new Error(error.response?.data?.message || '登录失败')
    }
  }

  const register = async (credentials) => {
    try {
      await axios.post('http://117.72.45.141:8091/api/user/register', credentials)
    } catch (error) {
      throw new Error(error.response?.data?.message || '注册失败')
    }
  }

  const logout = async () => {
    try {
      // 检查是否有token
      if (!token.value) {
        console.warn('未找到token，直接清除本地状态')
        clearUserState()
        return
      }

      // 调用后端退出接口
      const response = await axios.post('http://117.72.45.141:8091/api/main/logout', {}, {
        headers: {
          'Authorization': `Bearer ${token.value}`,
          'Content-Type': 'application/json'
        }
      })

      // 检查响应结果
      if (response.data.code === 200) {
        console.log('退出登录成功:', response.data.message)
      } else {
        console.warn('退出登录响应异常:', response.data.message)
      }

    } catch (error) {
      console.error('退出登录请求失败:', error)

      // 即使请求失败，也要清除本地状态
      if (error.response?.status === 401) {
        console.log('token已失效，清除本地状态')
      }
    } finally {
      // 无论成功还是失败，都清除本地状态并跳转
      clearUserState()
    }
  }

// 抽取清除状态的逻辑
  const clearUserState = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    router.push('/login')
  }

  const deleteAccount = async () => {
    try {
      const response = await axios.delete('http://117.72.45.141:8091/api/main/account', {
        headers: {
          Authorization: `Bearer ${token.value}`
        }
      })
      // 检查返回结果
      if (response.data && response.data.code === 200) {
        console.log(response.data.message || '账号注销成功')
        window.location.href = '/login'
        return response.data
      } else {
        // 虽然HTTP请求成功，但业务逻辑失败
        throw new Error(response.data?.message || '注销账号失败')
      }

    } catch (error) {
      // 处理不同类型的错误
      if (error.response) {
        const { status, data } = error.response
        switch (status) {
          case 500:
            // 服务器内部错误
            throw new Error(data?.message || '服务器内部错误')
          default:
            // 其他HTTP错误
            throw new Error(data?.message || `请求失败 (${status})`)
        }
      } else if (error.request) {
        throw new Error('网络连接失败，请检查网络连接')
      } else {
        throw new Error(error.message || '注销账号失败')
      }
    }
  }

  const setUser = (userData) => {
    user.value = userData
    localStorage.setItem('user', JSON.stringify(userData))
  }

  return { user, token, login, register, logout, deleteAccount }
})